﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.VisualStudio.TestTools.WebTesting;
using System.IO;
using QA.TFS.Utils;

namespace QA.TFS.Plugins.Request
{
    public class ExtractPDFTextRequest : WebTestRequestPlugin
    {

        private string _FileName = string.Empty;
        public string FileName
        {
            get { return _FileName; }
            set { _FileName = value; }
        }

        private string _RegEx = string.Empty;
        public string RegEx
        {
            get { return _RegEx; }
            set { _RegEx = value; }
        }

        private string _ContextParamName = string.Empty;
        public string ContextParamName
        {
            get { return _ContextParamName; }
            set { _ContextParamName = value; }
        }

        public override void PostRequest(object sender, PostRequestEventArgs e)
        {
            base.PostRequest(sender, e);

            string dir = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
            dir = System.IO.Path.Combine(dir, "VSTS");
            if (!Directory.Exists(dir))
                Directory.CreateDirectory(dir);

            string outFileName = dir + "/" + FileName + ".txt";
            e.WebTest.Context["TEST.OutputFile"] = outFileName;

            try
            {
                PDFParser parser = new PDFParser();
                string text = parser.ExtractText(e.Response.BodyBytes, outFileName);

                RegExHelper helper = new RegExHelper();
                helper.Regex = ContextParameterHelper.replaceContextParameters(e.WebTest.Context, RegEx);
                helper.UseIgnoreCase = false;
                helper.UseSingleline = false;
                helper.OnMatchFound += new RegExHelper.MatchDelegate(helper_OnMatchFound);
                helper.OnMatchNotFound += new RegExHelper.MatchErrorDelegate(helper_OnMatchNotFound);

                helper.ExtractValue(text, e);

            }
            catch (Exception ex)
            {
                throw new WebTestException("Extraccion fallida. " + ex.Message);
            }
        }

        void helper_OnMatchNotFound(EventArgs args)
        {
            ((PostRequestEventArgs)args).WebTest.Outcome = Outcome.Fail;
            ((PostRequestEventArgs)args).WebTest.Stop();
        }

        void helper_OnMatchFound(System.Text.RegularExpressions.MatchCollection collection, EventArgs args)
        {
            ((PostRequestEventArgs)args).WebTest.Context.Add(this.ContextParamName, collection[0].Groups[1].Value);
            ((PostRequestEventArgs)args).WebTest.Outcome = Outcome.Pass;
        }

    }
}
